﻿using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Configuration;

namespace hmi
{
    public class StopBitsBinding
    {
        public string Content { set; get; }
        public StopBits StopBitsValue { set; get; }               
    }

    public class ParityBinding
    {
        public string Content { set; get; } 
        public Parity ParityValue { set; get; }
    }

    /// <summary>
    /// OptionWindow.xaml 的交互逻辑
    /// </summary>
    public partial class SerialOptionWindow : Window
    {
        private static SerialOptionWindow instance;

        private static List<StopBitsBinding> _stopBitsBindingData = new List<StopBitsBinding>()
        {
            //new OptionBinding() {Content = "0", StopBitsValue = StopBits.None },
            new StopBitsBinding() {Content = "1", StopBitsValue = StopBits.One },
            //new OptionBinding() {Content = "1.5", StopBitsValue = StopBits.OnePointFive },
            new StopBitsBinding() {Content = "2", StopBitsValue = StopBits.Two },
        };

        public static List<StopBitsBinding> StopBitsBindingData
        {
            get
            {
                return _stopBitsBindingData;
            }
        }

        private static List<ParityBinding> _parityBindingData = new List<ParityBinding>()
        {
            new ParityBinding() {Content = "无", ParityValue = Parity.None },
            new ParityBinding() {Content = "奇校验", ParityValue = Parity.Odd },
            new ParityBinding() {Content = "偶校验", ParityValue = Parity.Even },
            new ParityBinding() {Content = "Mark", ParityValue = Parity.Mark },
            new ParityBinding() {Content = "空格校验", ParityValue = Parity.Space },
        };

        public static List<ParityBinding> ParityBindingData
        {
            get
            {
                return _parityBindingData;
            }
        }
        public static SerialOptionWindow CreateWindow()
        {
            if (instance == null)
            {
                instance = new SerialOptionWindow();
            }
            return instance;
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            instance = null;
        }

        private SerialOptionWindow()
        {            
            InitializeComponent();
        }        

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            DisplayInit();
            PortRefresh();            
        }

        private void PortRefresh()//刷新可用串口
        {
            PortNumCbobox.Items.Clear();
            string[] portNames = SerialPort.GetPortNames();//获取可用串口
            if (portNames.Length > 0)//有串口可用
            {
                for (int i = 0; i < portNames.Length; i++)
                {
                    PortNumCbobox.Items.Add(portNames[i]);//下拉控件里添加可用串口                    
                }
                string portNumStr = ConfigurationManager.AppSettings["PortNum"];
                if (portNumStr == "" || !portNames.Contains(portNumStr))
                {
                    PortNumCbobox.SelectedIndex = 0;//没有串口存储值或者当前可选串口中未包含存储值,默认选取可选的第一个串口
                }
                else
                {
                    PortNumCbobox.Text = portNumStr;
                }
            }
            else//未检测到串口
            {
                MessageBox.Show("无可用串口");
            }
        }

        private void DisplayInit()
        {            
            BaudRateCbobox.Text = ConfigurationManager.AppSettings["BaudRate"];//波特率
            DataBitsCbobox.Text = ConfigurationManager.AppSettings["DataBits"];//数据位
            StopBitsCbobox.SelectedValue = (StopBits)Convert.ToInt32(ConfigurationManager.AppSettings["StopBits"]);//停止位
            ParityCbobox.SelectedValue = (Parity)Convert.ToInt32(ConfigurationManager.AppSettings["Parity"]);//校验位默认设置值为偶校验
            InitOpenBtn();
        }

        private void InitOpenBtn()
        {
            if (CommManage.Instance.CommTool.IsOpen)
            {                
                OpenBtn.Content = "关闭";
                OpenImage.Source = new BitmapImage(new Uri("image\\On.png", UriKind.Relative));//开关状态图片切换为ON
            }
            else
            {
                OpenBtn.Content = "打开";
                OpenImage.Source = new BitmapImage(new Uri("image\\Off.png", UriKind.Relative));//开关状态图片切换为off
            }
        }

        private void SetPara()
        {            
            var serPort = ((SerialComm)(CommManage.Instance.CommTool)).Port;
            serPort.PortName = PortNumCbobox.Text.ToString();//设置要打开的串口
            serPort.BaudRate = Convert.ToInt32(BaudRateCbobox.Text);//设置当前波特率
            serPort.DataBits = Convert.ToInt32(DataBitsCbobox.Text);//设置当前数据位
            serPort.StopBits = (StopBits)StopBitsCbobox.SelectedValue;//设置当前停止位
            serPort.Parity = (Parity)ParityCbobox.SelectedValue;//设置当前校验位
        }

        private void SaveConfigure()
        {            
            Configuration configure = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            configure.AppSettings.Settings["PortNum"].Value = PortNumCbobox.Text;
            configure.AppSettings.Settings["BaudRate"].Value = BaudRateCbobox.Text;
            configure.AppSettings.Settings["DataBits"].Value = DataBitsCbobox.Text;
            configure.AppSettings.Settings["StopBits"].Value = Convert.ToInt32(StopBitsCbobox.SelectedValue).ToString();
            configure.AppSettings.Settings["Parity"].Value = Convert.ToInt32(ParityCbobox.SelectedValue).ToString();
            configure.Save();
            ConfigurationManager.RefreshSection("appSettings");
        }            

        private void OpenBtn_Click(object sender, RoutedEventArgs e)
        {
            if (CommManage.Instance.IsUdp)
            {
                return;
            }
            if ((string)OpenBtn.Content == "打开")
            {
                string[] portNames = SerialPort.GetPortNames();//获取可用串口
                if (portNames.Length <= 0)//未检测到串口
                {
                    MessageBox.Show("无可用串口");
                    PortRefresh();
                    return;
                }
                if (portNames.Contains(PortNumCbobox.Text) == false)
                {
                    MessageBox.Show("当前选择串口已经断开连接");
                    PortRefresh();
                    return;
                }
                SetPara();
                
                CommManage.Instance.CommTool.Open();
                if (!CommManage.Instance.CommTool.IsCommRight)
                {
                    MessageBox.Show("通信端口<" + ((SerialComm)(CommManage.Instance.CommTool)).Port.PortName + ">无法打开！请检查此串口是否有效或被占用！");
                    return;
                }

                SaveConfigure();
                OpenBtn.Content = "关闭";
                OpenImage.Source = new BitmapImage(new Uri("image\\On.png", UriKind.Relative));//开关状态图片切换为ON
            }
            else if ((string)OpenBtn.Content == "关闭")
            {
                //SerialComm.Instance.Close();
                CommManage.Instance.CommTool.Close();
                OpenBtn.Content = "打开";
                OpenImage.Source = new BitmapImage(new Uri("image\\Off.png", UriKind.Relative));//开关状态图片切换为off                
            }                        
        }
    }
}
